import os,json
from kubernetes import client, config
from kubernetes.client.rest import ApiException
import datetime
import pytz

config.load_kube_config(
    os.path.join(os.environ["HOME"], '.kube/config'))

class KubeClient:
    def __init__(self):
        self.v1 = client.AppsV1Api()
        self.v1Core = client.CoreV1Api()

    def list_all_namespace_deploy(self):
        try:
            resp = self.v1.list_deployment_for_all_namespaces()
        except ApiException as e:
            print("Exception when calling AppsV1Api->list_namespaced_deployment: %s\n" % e)
        return resp

    def create_namespaced_deploy(self,namespace,dep):
        resp = self.v1.create_namespaced_deployment(
            body=dep, namespace=namespace)
        print("Deployment created. status='%s'" % resp.metadata.name)

    def update_namespaced_deploy(self,deployment_name,namespace,dep):
        resp = self.v1.replace_namespaced_deployment(
            name=deployment_name, namespace=namespace, body=dep
        )
        print("\n[INFO] deployment's container image updated.\n")
        print("%s\t%s\t\t\t%s\t%s" % ("NAMESPACE", "NAME", "REVISION", "IMAGE"))
        print(
            "%s\t\t%s\t%s\t\t%s\n"
            % (
                resp.metadata.namespace,
                resp.metadata.name,
                resp.metadata.generation,
                resp.spec.template.spec.containers[0].image,
            )
        )
        return resp

    def delete_namespaced_deploy(self, deployment_name,namespace):
        resp = self.v1.delete_namespaced_deployment(
            name=deployment_name,
            namespace=namespace,
            body=client.V1DeleteOptions(
                propagation_policy="Foreground", grace_period_seconds=5
            ),
        )
        print("\n[INFO] deployment `nginx-deployment` deleted.")

    def list_node(self):
        host_list = []
        try:
            resp = self.v1Core.list_node()
        except ApiException as e:
            print("Exception when calling CoreV1Api->list_node: %s\n" % e)
        for i in resp.items:
            host = {}
            for c in i.status.conditions:
                if c.type == "Ready":
                    host['status'] = c.status
            for s in i.status.addresses:
                if s.type == 'InternalIP':
                    host['ipaddr'] = s.address
                else:
                    host['hostname'] = s.address
            host_list.append(host)

        return host_list

    def patch_label(self,body):
        try:
            resp = self.v1Core.patch_node("node1", body)
        except ApiException as e:
            print("Exception when calling CoreV1Api->list_node: %s\n" % e)

if __name__ == "__main__":
    # with open("../test/k8s.json", 'r') as load_f:
    # k = KubeClient()
    body = {
        "metadata": {
            "labels": {
                "training": None}
            }
    }
    # api_response = k.patch_label(body)
    # print(api_response)
